﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.ComponentModel;
using System.Web;
using System.Web.UI;

namespace UOL.PagSeguro {

    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultEvent("VendaEfetuada")]
    [DefaultProperty("Token")]
    [Description("Processa o retorno automático de uma venda através do UOL PagSeguro")]
    [Designer(typeof(Design.RetornoPagSeguroDesigner))]
    public class RetornoPagSeguro : Control {

        public delegate void VendaEfetuadaEventHandler(RetornoVenda retornoVenda);
        public event VendaEfetuadaEventHandler VendaEfetuada;

        /// <summary>
        /// Token de Segurança
        /// </summary>
        public string Token { get; set; }

        public RetornoPagSeguro() {

        }

        public RetornoPagSeguro(string token)
            : this() {
            this.Token = token;
        }

        protected override void OnLoad(EventArgs e) {
            if (this.Page != null) {
                string requestContent = this.Page.Request.Form.ToString() + "&Comando=validar&Token=" + this.Token;
                HttpWebRequest NPIRequest = (HttpWebRequest)WebRequest.Create(Resources.PagSeguro_NPI);
                NPIRequest.Method = WebRequestMethods.Http.Post;
                NPIRequest.ContentLength = requestContent.Length;

                StreamWriter writer = new StreamWriter(NPIRequest.GetRequestStream(), System.Text.Encoding.Default);
                writer.Write(requestContent);
                writer.Close();

                StreamReader reader = new StreamReader(NPIRequest.GetResponse().GetResponseStream(), Encoding.UTF8);
                string NPIResponse = reader.ReadToEnd();
                reader.Close();

                if ("VERIFIED".Equals(NPIResponse)) {
                    this.VendaEfetuada(RetornoVenda.CriarViaRespostaNPI(this.Page.Request.Form));
                }
            }
        }
    }
}
